// localLifePackage/pages/businessList/businessList.js
var {$author: $author} = require("../../../components/base/authorization.js");

var common = require("../../../common/common.js").common;

var QQMapWX = require("../../../sdk/qqmap-wx-jssdk.min.js");

var customLink = require("../../../common/customLink.js");

var {$author: $author} = require("../../../components/base/authorization.js");

var app = getApp();

Page({
    /**
   * 页面的初始数据
   */
    data: {
        offOpenTip: true,
        page: 1,
        //当前页
        rows: 10,
        //分页大小
        total: 0,
        loading: true,
        storeList: [],
        addressName: "获取位置",
        latitude: 0,
        //经度
        longitude: 0,
        //纬度
        now_address: "",
        showTip: false,
        nav_style: 1,
        //1文字分类 2图标分类
        cate_id: "-1",
        businessListFlag: true
    },
    //页面下拉
    onPageScroll: function(e) {
        let that = this;
        const query = wx.createSelectorQuery().in(this);
        query.select("#list_box").boundingClientRect();
        query.selectViewport().scrollOffset();
        query.exec(function(res) {
            if (res[0]) {
                var scrollLen = 30;
                if (that.data.imgUrls2.length) {
                    scrollLen = 310;
                }
                if (res[0].top <= scrollLen) {
                    that.setData({
                        nav_style: 1
                    });
                } else {
                    that.setData({
                        nav_style: that.data.getNavData.styleData.local_style
                    });
                }
            }
        });
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        wx.hideShareMenu();
        this.setData({
            domain: app.globalData.domain.slice(0, -10)
        });
        this.getClassify();
        this.getSow();
        //轮播图
                this.getBase();
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {},
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {
        let that = this;
        that.getClassify();
        that.setData({
            page: 1,
            storeList: [],
            cate_id: "-1"
        });
        that.getBusinessData();
        wx.stopPullDownRefresh();
    },
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {
        this.getBusinessData();
    },
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {},
    //全局基础配置信息
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                var goodsListStyle = that.data.goodsListStyle;
                // wx.setNavigationBarColor({
                //   frontColor: "#ffffff",
                //   backgroundColor: res.extra.color_main
                // })
                                that.setData({
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    apptitle: res.extra.title,
                    style: res.extra.style,
                    new_member_audit: res.extra.new_member_audit,
                    userAuditStatus: res.extra.userAuditStatus ? res.extra.userAuditStatus : 2,
                    list_style: res.extra.list_style,
                    timeStyle: {
                        height: 32,
                        mainColor: res.extra.color_main
                    },
                    goodsListStyle: {
                        ...goodsListStyle,
                        mainColor: res.extra.color_main
                    }
                });
                this.getLocalView();
            }
        });
    },
    // 轮播图
    getSow: function() {
        var that = this;
        common.request({
            endpoint: "Localbusiness/common/link_object",
            method: "post",
            success: res => {
                var imgUrls2 = [];
                if (res.extra[0]) {
                    imgUrls2 = res.extra[0].img;
                }
                that.setData({
                    imgUrls2: imgUrls2
                });
            }
        });
    },
    //跳转页面
    goToPages(e) {
        var that = this;
        common.getUserInfoNew({
            success() {
                customLink(e.detail.itemData);
            }
        });
    },
    openTip(e) {
        let that = this;
        var idx = e.currentTarget.dataset.index;
        var storeList = that.data.storeList;
        if (!!storeList[idx].offOpenTip) {
            storeList[idx].offOpenTip = false;
            that.setData({
                storeList: storeList
            });
        } else {
            storeList[idx].offOpenTip = true;
            that.setData({
                storeList: storeList
            });
        }
    },
    searchBusiness(e) {
        let that = this;
        let keyword = e.detail.value;
        that.setData({
            keyword: keyword,
            storeList: [],
            page: 1
        });
        that.getBusinessData2();
        // let storeList = this.data.storeList;
        // storeList.map(function (v, i) {
        //   let itemHidden;
        //   if (v.name.match(keyword) || v.category.match(keyword)) {
        //     v.itemHidden = false;
        //   } else {
        //     v.itemHidden  = true;
        //   }
        //   // return Object.assign(v, { itemHidden: itemHidden })
        // })
        // this.setData({
        //   storeList: storeList
        // })
        },
    toBusinessDetail(e) {
        if (this.data.userAuditStatus != 2 && this.data.new_member_audit == 1) {
            wx.showModal({
                title: "提示",
                content: "你还不是会员，请先到个人中心申请吧！",
                showCancel: false
            });
            return false;
        }
        common.getUserInfoNew({
            success() {
                wx.navigateTo({
                    url: "/localLifePackage/pages/businessInfo/businessInfo?merchant_id=" + e.currentTarget.dataset.item.id
                });
            }
        });
    },
    getClassify: function() {
        var that = this;
        common.request({
            endpoint: "Localbusiness/merchant/classify",
            method: "post",
            data: {},
            success: res => {
                if (res.extra) {
                    var navData = [];
                    res.extra.list.map(x => {
                        if (x.category_name == "全部") {
                            x.id = "-1";
                        }
                    });
                    if (!!res.extra.list) {
                        navData.push(res.extra.list);
                    }
                    if (!!res.extra.list) {
                        that.setData({
                            nav_style: res.extra.style.local_style == 1 ? 1 : 2,
                            classList: res.extra.list,
                            getNavData: {
                                navData: navData,
                                styleData: {
                                    ...res.extra.style
                                }
                            }
                        });
                    }
                }
            }
        });
    },
    getBusinessData2: function() {
        var that = this;
        that.setData({
            businessListFlag: true
        });
        if (that.data.list_style == 1) {
            common.request({
                endpoint: "Localbusiness/merchant/merchant-list",
                method: "post",
                data: {
                    position: that.data.latitude + "," + that.data.longitude,
                    rows: that.data.rows,
                    page: that.data.page,
                    keyword: that.data.keyword,
                    cate_id: that.data.cate_id
                },
                success: res => {
                    that.setData({
                        businessListFlag: false
                    });
                    console.log(res);
                    let storeList = res.extra.rows;
                    if (storeList.length > 0) {
                        this.setData({
                            storeList: storeList,
                            page: that.data.page + 1
                        });
                    }
                }
            });
        } else {
            common.request({
                endpoint: "v1/Localbusiness/merchant",
                method: "post",
                data: {
                    position: that.data.latitude + "," + that.data.longitude,
                    "per-page": that.data.rows,
                    page: that.data.page,
                    keyword: that.data.keyword,
                    cate_id: that.data.cate_id
                },
                success: res => {
                    that.setData({
                        businessListFlag: false
                    });
                    console.log(res);
                    let storeList = res.extra.rows;
                    if (storeList.length > 0) {
                        this.setData({
                            storeList: storeList,
                            page: that.data.page + 1
                        });
                    }
                }
            });
        }
    },
    getBusinessData: function() {
        var that = this;
        that.setData({
            businessListFlag: true
        });
        if (that.data.list_style == 1) {
            common.request({
                endpoint: "Localbusiness/merchant/merchant-list",
                method: "post",
                data: {
                    position: that.data.latitude + "," + that.data.longitude,
                    rows: that.data.rows,
                    page: that.data.page,
                    keyword: that.data.keyword,
                    cate_id: that.data.cate_id
                },
                success: res => {
                    that.setData({
                        businessListFlag: false
                    });
                    console.log(res);
                    let storeList = res.extra.rows;
                    if (storeList.length > 0) {
                        storeList = that.data.page == 1 ? storeList : that.data.storeList.concat(storeList);
                        storeList.map(x => {
                            x.products.map(y => {
                                y.really_sale = Number(y.virtual_monthly_sales) + Number(y.sale_volume);
                            });
                        });
                        this.setData({
                            storeList: storeList,
                            page: that.data.page + 1
                        });
                    }
                }
            });
        } else {
            common.request({
                endpoint: "v1/Localbusiness/merchant",
                method: "post",
                data: {
                    position: that.data.latitude + "," + that.data.longitude,
                    "per-page": that.data.rows,
                    page: that.data.page,
                    keyword: that.data.keyword,
                    cate_id: that.data.cate_id
                },
                success: res => {
                    that.setData({
                        businessListFlag: false
                    });
                    console.log(res);
                    let storeList = res.extra.rows;
                    if (storeList.length > 0) {
                        storeList = that.data.page == 1 ? storeList : that.data.storeList.concat(storeList);
                        this.setData({
                            storeList: storeList,
                            page: that.data.page + 1
                        });
                    }
                }
            });
        }
    },
    toPageDetail: function(e) {
        let stock = e.currentTarget.dataset.stock;
        let is_alive = e.currentTarget.dataset.isalive;
        let id = e.currentTarget.dataset.id;
        let pro_id = e.currentTarget.dataset.proid;
        if (!is_alive) {
            wx.showModal({
                title: "提示",
                content: "该商家休息中，无法购买!",
                showCancel: false
            });
            return;
        }
        if (stock <= 0) {
            wx.showModal({
                title: "提示",
                content: "库存不足!",
                showCancel: false
            });
            return;
        }
        wx.navigateTo({
            url: "/localLifePackage/pages/pro_detail/pro_detail?merchant_id=" + id + "&pro_id=" + pro_id
        });
    },
    changeAddress: function() {
        var that = this;
        wx.chooseLocation({
            success: function(res) {
                console.log(res);
                that.setData({
                    addressName: res.name,
                    latitude: res.latitude,
                    longitude: res.longitude,
                    page: 1,
                    limit: 10,
                    storeList: []
                });
                that.getBusinessData();
            },
            fail: function(err) {
                console.log(err);
                wx.showModal({
                    title: "提示",
                    content: "地理位置调用失败,是否重新授权!",
                    success(res) {
                        if (res.confirm) {
                            that.continueGetSet();
                        } else if (res.cancel) {
                            console.log("用户点击取消");
                        }
                    }
                });
            }
        });
    },
    continueGetSet: function() {
        let that = this;
        wx.getSetting({
            success(res) {
                console.log(res);
            }
        });
        wx.openSetting({
            success(res) {
                console.log(res);
                if (res.authSetting["scope.userLocation"]) {
                    that.changeAddress();
                    that.setData({
                        showTip: false
                    });
                }
            }
        });
    },
    getLocalView: function() {
        var that = this;
        common.getAppBase().then(() => {
            var qqmapsdk = new QQMapWX({
                key: that.data.appBase.location_key
            });
            wx.getLocation({
                type: "gcj02",
                isHighAccuracy: true,
                success: function(res) {
                    that.setData({
                        latitude: res.latitude,
                        longitude: res.longitude
                    });
                    qqmapsdk.reverseGeocoder({
                        location: {
                            latitude: res.latitude,
                            longitude: res.longitude
                        },
                        success: function(res) {
                            //获取当前地址成功
                            that.setData({
                                addressName: res.result.address
                            });
                            that.getBusinessData();
                        },
                        fail: function(res) {
                            console.log("获取当前地址失败");
                        }
                    });
                },
                fail: function(res) {
                    wx.showModal({
                        title: "提示",
                        content: "地理位置调用失败,是否重新授权!",
                        success(res) {
                            if (res.confirm) {
                                that.continueGetSet();
                            } else if (res.cancel) {
                                that.setData({
                                    showTip: true
                                });
                            }
                        }
                    });
                    that.setData({
                        showTip: true
                    });
                }
            });
        });
    },
    chooseNav: function(options) {
        let that = this;
        let id = options.detail.id;
        that.setData({
            cate_id: id,
            page: 1,
            storeList: []
        });
        that.getBusinessData();
    },
    chooseClass: function(e) {
        let that = this;
        let id = e.currentTarget.dataset.id;
        that.setData({
            cate_id: id,
            page: 1,
            storeList: []
        });
        that.getBusinessData();
    }
});